<template>
  <Dialog
      :show="dialogConfig.show"
      :title="dialogConfig.title"
      :buttons="dialogConfig.buttons"
      :showCancel="true"
      width="80%"
      @close="dialogConfig.show = false"
  >
    <el-form
        :model="formData"
        :rules="rules"
        ref="formDataRef"
        label-width="80px"
        @submit.prevent
    >
      <el-row :gutter="10">
        <el-col :span="10">
          <el-form-item label="标题" prop="title">
            <el-input :maxLength="10" v-model="formData.title"/>
          </el-form-item>
          <el-form-item label="分类" prop="categoryId">
            <CategorySelect
                v-model="formData.categoryId"
                :type="0"
            ></CategorySelect>
          </el-form-item>
          <el-form-item label="难度" prop="difficultyLevel">
            <el-rate v-model="formData.difficultyLevel"></el-rate>
          </el-form-item>
          <el-form-item label="问题类型" prop="questionType">
            <el-radio-group v-model="formData.questionType">
              <el-radio
                  v-for="item in questionTypeList"
                  :label="item.value"
                  @change="resetAnswer"
              >{{ item.text }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <!--    问题选项      -->
          <el-form-item label="答案选项" v-if="formData.questionType && formData.questionType !== 0">
            <div
                class="question-item"
                v-for="(item,index) in formData.questionItemList"
            >
              <div class="letter">
                {{ LETTER[index] }}
              </div>
              <div class="title">
                <el-form-item
                    label-width="0px"
                    :key="index"
                    :prop="`questionItemList[${index}].title`"
                    :rules="{
                      required:true,
                      message:'答案选项不能为空'
                }">
                  <el-input
                      v-model="item.title"
                      clearable
                      placeholder="请输入答案选项内容"></el-input>
                </el-form-item>
              </div>
              <div class="op">
                <span v-if="index===0"
                      @click="addQuestionItem()">+</span>
                <span v-if="index!==0 && index===formData.questionItemList.length-1"
                      @click="delQuestionItem(index)">-</span>
              </div>
            </div>
          </el-form-item>
          <!--    答案区域      -->
          <el-form-item label="答案" prop="questionAnswer">
            <!-- 判断题 -->
            <template v-if="currentQuestionType === 0">
              <el-radio-group v-model="formData.questionAnswer">
                <el-radio :label="1">正确</el-radio>
                <el-radio :label="0">错误</el-radio>
              </el-radio-group>
            </template>
            <!-- 单选题 -->
            <template v-if="currentQuestionType === 1">
              <el-radio-group v-model="formData.questionAnswer">
                <el-radio
                    v-for="(item,index) in formData.questionItemList"
                    :label="index"
                >{{ LETTER[index] }}
                </el-radio>
              </el-radio-group>
            </template>
            <!-- 多选题 -->
            <template v-if="currentQuestionType === 2">
              <el-checkbox-group v-model="formData.questionAnswer">
                <el-checkbox
                    v-for="(item,index) in formData.questionItemList"
                    :label="index"
                >{{ LETTER[index] }}
                </el-checkbox>
              </el-checkbox-group>
            </template>
          </el-form-item>
        </el-col>
        <el-col :span="14">
          <el-form-item label="问题描述" prop="content">
            <SunEditor :height="220" v-model="formData.question"></SunEditor>
          </el-form-item>
          <el-form-item label="答案解析" prop="answerAnalysis">
            <SunEditor :height="220" v-model="formData.answerAnalysis"></SunEditor>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </Dialog>
</template>


<script setup>
import {computed, getCurrentInstance, nextTick, ref} from "vue";
import {LETTER, QUESTION_TYPE} from "@/utils/constants.js";

const {proxy} = getCurrentInstance();

const formData = ref({});
const formDataRef = ref();
const rules = {
  title: [{required: true, message: "请输入标题"}],
  categoryId: [{required: true, message: "请选择分类"}],
  difficultyLevel: [{required: true, message: "请输选择难度"}],
  answerAnalysis: [{required: true, message: "请输入答案解析"}],
  questionType: [{required: true, message: "请选择问题类型"}],
  questionAnswer: [{required: true, message: "请选择答案"}],
}

const emit = defineEmits()

// 问题类型数组
const questionTypeList = computed(() => {
  return Object.entries(QUESTION_TYPE).map(([key, value]) => ({value: parseInt(key), text: value}));
})

const showEdit = (data) => {
  dialogConfig.value.show = true;
  nextTick(async () => {

    dialogConfig.value.title = data.questionId ? '修改问题' : '添加问题';
    formData.value = Object.assign(
        {},
        data
    );
    formData.value.questionItemList = [{
      title: "",
      sort: 1
    }]
    if (data.questionId) {
      // 获取问题选项
      let result = await proxy.Request({
        url: "/examQuestion/loadQuestionItem",
        params: {
          questionId: data.questionId
        },
      })
      if (!result) {
        return;
      }
      formData.value.questionItemList = result.data.map(item => item);
      currentQuestionType.value = parseInt(data.questionType);
      // 多选题答案
      if (data.questionType === 2) {
        formData.value.questionAnswer = formData.value.questionAnswer.split(",").map(Number);
      } else {
        formData.value.questionAnswer = parseInt(data.questionAnswer);
      }
    }


  })
}

// 编辑问题 提交
const editQuestion = async () => {
  formDataRef.value.validate(async (valid) => {
        if (!valid) {
          return;
        }
        // 判断答案选择是否存在
        if (formData.value.questionAnswer && formData.value.questionType !== 0) {
          let questionAnswerArray = [];
          if (formData.value.questionAnswer instanceof Array) {
            questionAnswerArray = formData.value.questionAnswer;
          } else {
            questionAnswerArray = formData.value.questionAnswer.split(",");
          }
          questionAnswerArray.forEach((element, index) => {
            if (formData.value.questionItemList.length - 1 < Number.parseInt(element)) {
              if (formData.value.questionType === 1) {
                formData.value.questionAnswer = null;
              }
              if (formData.value.questionType === 2) {
                formData.value.questionAnswer.splice(index, 1);
              }
            }
          })
        }

        let params = {...formData.value};

        // 判断问题选项是否重复
        if (isRepeat(params.questionItemList)) {
          proxy.Message.warning("答案选项内容重复");
          return;
        }

        // 把值转换为 json
        if (params.questionType === 2) {
          params.questionAnswer = params.questionAnswer.sort().join(",");
        }
        if (params.questionType !== 0) {
          params.questionItemListJson = JSON.stringify(params.questionItemList);
        }
        delete params.questionItemList;

        let result = await proxy.Request({
          url: "/examQuestion/saveExamQuestion",
          params,
        })
        if (!result) {
          return;
        }
        proxy.Message.success(`${formData.value.questionId ? '修改' : '添加'}问题成功`);
        // proxy.Message.success(`添加问题成功`);
        formData.value = {};
        currentQuestionType.value = '';
        dialogConfig.value.show = false;
        emit("reload");
      }
  )
}

// 判断问题选项是否重复
const isRepeat = (arr) => {
  let tempMap = {};
  for (let i in arr) {
    if (tempMap[arr[i].title]) {
      return true;
    }
    tempMap[arr[i].title] = true;
  }
  return false;
}

// 添加回答
const addQuestionItem = () => {
  if (formData.value.questionItemList.length > 26) {
    proxy.Message.success("最多添加26个选项")
    return;
  }
  formData.value.questionItemList.push({
    title: "",
    sort: formData.value.questionItemList.length + 1
  })
}
// 删除回答
const delQuestionItem = (index) => {
  formData.value.questionItemList.splice(index, 1)
}

// 修改问题类型
const currentQuestionType = ref();
const resetAnswer = (e) => {
  if (e === 2) {
    formData.value.questionAnswer = [];
  } else {
    formData.value.questionAnswer = "";
  }
  currentQuestionType.value = e;
  console.log(currentQuestionType.value)
}

// 配置
const dialogConfig = ref({
  show: false,
  buttons: [{
    text: "确定",
    type: "primary",
    click: editQuestion
  }],
  title: "添加问题",
  showClose: true
});

defineExpose({
  showEdit
})
</script>


<style scoped lang="scss">
.question-item {
  display: flex;
  width: 100%;
  margin-top: 20px;

  .letter {
    width: 10px;
    text-align: center;
    margin-right: 10px;
  }

  .title {
    flex: 1;
  }

  .op {
    width: 25px;
    text-align: center;
    font-size: 25px;

    span {
      cursor: pointer;

    }
  }
}

.question-item:first-child {
  margin-top: 0;
}
</style>
